<template>
  <view scroll-y="true" class="my-exam ldBg">
    <view class="uni-padding-wrap uni-common-mt tab">
      <uni-segmented-control
        :current="current"
        :values="['正式考试', '模拟考试']"
        :style-type="styleType"
        :active-color="activeColor"
        @clickItem="onClickItem"
      />
    </view>
    <view class="content">
      <view v-if="current === 0">
        <uni-list class="list_content">
          <view
            class="card data_card"
            v-for="myExam in listpage.list"
            :key="myExam.examId"
            @click="toExam(myExam)"
          >
            <view class="test_time">
              {{ myExam.examName }}
            </view>
            <view class="test_time_1">
              <span class="title" style="color: #999">开始时间：</span>
              <span class="timeInfo">{{ myExam.examStartTime?.replace(/:\d\d$/, "")  }}</span>
            </view>
            <view class="test_time_1">
              <span class="title" style="color: #999">截止时间：</span>
              <span class="timeInfo">{{ myExam.examEndTime?.replace(/:\d\d$/, "")  }}</span>
            </view>
            <view class="test_card_status">
              <view class="test_status_info">
                <span class="num">
                  分数：{{
                    myExam.totalScore == null ? "-" : myExam.totalScore
                  }}
                  / {{ myExam.examTotalScore }}
                </span>

                <span class="time">
                  考试时长：{{ myExam.examPassTime }}分钟
                </span>

                <span
                  v-if="myExam.myExamState == 1"
                  style="color: #000"
                  class="state"
                  >待考试</span
                >
                <span
                  v-else-if="myExam.myExamState == 2"
                  style="color: #24b0fb"
                  class="state"
                  >进行中</span
                >
              </view>
              <span v-if="myExam.myExamState == 3" class="state imgState">
                <image src="/static/yitongguo.png" class="stateImg"
              /></span>
              <span v-else-if="myExam.myExamState == 4" class="state imgState">
                <image src="/static/weitongguo.png" class="stateImg" />
              </span>
            </view>
          </view>
        </uni-list>
        <uni-load-more
          class="myLoad"
          :status="listpage.status"
          :contentText="{
            contentdown: '点击查看更多',
            contentrefresh: '加载中',
            contentnomore: '到底了',
          }"
          @clickLoadMore="query(true)"
        ></uni-load-more>
      </view>
      <view v-if="current === 1">
        <view class="tip">
          注：长按删除模拟考试记录
        </view>
        <uni-list class="list_content">
          <view
            class="card data_card"
            v-for="myExam in listpage2.list"
            :key="myExam.examId"
            @click="toMock(myExam)"
            @touchstart="(event) => onTouchStart(event, myExam)"
            @touchmove="onTouchMove"
            @touchend="onTouchEnd"
          >
            <view class="test_time">
              {{ myExam.paperName }}
            </view>
            <view class="test_time_1 test_time_c">
              <span class="title" style="color: #999">截止时间：</span>
              <span class="timeInfo" v-if="myExam.state == 3">{{
                myExam.answerEndTime?.replace(/:\d\d$/, "") 
              }}</span>
              <span class="timeInfo" v-else>{{
                calculateTimeDifference(myExam.answerStartTime, myExam.passTime)
              }}</span>
            </view>
            <view class="test_card_status test_time_c">
              <view class="mockB test_status_info">
                <span class="num">
                  分数：{{
                    myExam.totalScore == null ? "-" : myExam.totalScore
                  }}
                  / {{ myExam.examTotalScore }}
                </span>
                <span class="time"> 考试时长：{{ myExam.passTime }}分钟 </span>
                <span
                  v-if="myExam.myExamState == 1"
                  style="color: #000"
                  class="state"
                  >待考试</span
                >
                <span
                  v-else-if="myExam.myExamState == 2"
                  style="color: #24b0fb"
                  class="state"
                  >进行中</span
                >
              </view>
              <span v-if="myExam.myExamState == 3" class="state imgState">
                <image src="/static/yitongguo.png" class="stateImg"
              /></span>
              <span v-else-if="myExam.myExamState == 4" class="state imgState">
                <image src="/static/weitongguo.png" class="stateImg" />
              </span>
            </view>
          </view>
        </uni-list>
        <uni-load-more
          :status="listpage2.status"
          :contentText="{
            contentdown: '点击查看更多',
            contentrefresh: '加载中',
            contentnomore: '到底了',
          }"
          @clickLoadMore="query1(true)"
        ></uni-load-more>
      </view>
    </view>
    <uni-popup ref="alertDialog" type="dialog">
      <uni-popup-dialog
        cancelText="关闭"
        confirmText="删除"
        title="通知"
        content="确认删除该场模拟考试？"
        @confirm="dialogConfirm"
        @close="dialogCancel"
      ></uni-popup-dialog>
    </uni-popup>
  </view>
</template>

<script lang="ts" setup>
import { reactive, ref, onUnmounted } from "vue";
import {
  onLoad,
  onShow,
  onPullDownRefresh,
  onReachBottom,
  destroyed,
} from "@dcloudio/uni-app";
import { MyExam } from "@/ts";
import http from "@/utils/request";
import { useDictStore } from "@/stores/dict";
import { noticStore } from "@/stores/notic";

// 定义变量
const alertDialog = ref();
const activeColor = ref("#24b0fb");
const dictStore = useDictStore();
const noticFn = noticStore();
const queryForm = reactive({
  // 查询表单
  examName: "", // 考试名称
});
const current = ref(0); // 当前选中的选项卡
const delExamId = ref(""); // 删除的考试id
const listpage = reactive({
  // 分页列表
  curPage: 1,
  pageSize: 10,
  total: 0,
  list: [] as MyExam[],
  status: "more",
});

const listpage2 = reactive({
  // 分页列表
  curPage: 1,
  pageSize: 10,
  total: 0,
  list: [],
  status: "more",
});

// 页面加载完毕，执行如下方法
onLoad(async (option) => {});
onShow(async (option) => {
  current.value = noticFn.tabIndex;
  getData();
});
onPullDownRefresh(async () => {
  //根据选中的选项卡，刷新数据
  getData();
});
onReachBottom(() => {
  if (current.value === 0) {
    //判断是否还有更多数据
    if (listpage.status === "more") {
      query(true);
    }
  } else {
    //判断是否还有更多数据
    if (listpage2.status === "more") {
      query1(true);
    }
  }
});
const getData = () => {
  //从第一页开始

  if (current.value === 0) {
    listpage.curPage = 1;
    //清除原有数据
    listpage.list = [];

    query(false); // 正式考试
  } else {
    listpage2.curPage = 1;
    //清除原有数据
    listpage2.list = [];

    query1(false); // 模拟考试
  }
  noticFn.tabIndex = 0;
};

/**
 * 查询
 *
 * @param append 追加数据
 */
async function query(append: boolean) {
  listpage.status = "loading";
  if (append) {
    listpage.curPage++;
  } else {
    listpage.curPage = 1;
  }

  const { code, data } = await http.post("myExam/listpage", {
    ...queryForm,
    curPage: listpage.curPage,
    pageSize: listpage.pageSize,
  });

  if (code !== 200) {
    return;
  } else {
    uni.stopPullDownRefresh();
  }

  listpage.total = data.total;

  if (append) {
    if (data.list.length) {
      listpage.list.push(...data.list);
    }
  } else {
    listpage.list = data.list;
  }

  // 将列表中的examStartTime 最后两位秒去掉


  if (listpage.list.length < listpage.total) {
    listpage.status = "more";
  } else {
    listpage.status = "no-more";
  }
}
async function query1(append: boolean) {
  listpage2.status = "loading";
  if (append) {
    listpage2.curPage++;
  } else {
    listpage2.curPage = 1;
  }

  const { code, data } = await http.post("myExamMock/listpage", {
    ...queryForm,
    curPage: listpage2.curPage,
    pageSize: listpage2.pageSize,
  });

  if (code !== 200) {
    return;
  } else {
    uni.stopPullDownRefresh();
  }

  listpage2.total = data.total;

  if (append) {
    if (data.list.length) {
      listpage2.list.push(...data.list);
    }
  } else {
    listpage2.list = data.list;
  }



  if (listpage2.list.length < listpage2.total) {
    listpage2.status = "more";
  } else {
    listpage2.status = "no-more";
  }
}

// 去考试
async function toExam(myExam: MyExam) {
  let { data } = await http.post("login/sysTime", {});
  let curTime = new Date(data.replaceAll("-", "/"));
  let examStartTime = new Date(myExam.examStartTime.replaceAll("-", "/"));
  if (examStartTime.getTime() > curTime.getTime()) {
    uni.showToast({ title: "考试未开始，请等待...", icon: "none" });
    return;
  }

  uni.navigateTo({ url: `/pages/myExam/myExamPage?examId=${myExam.examId}` });
  noticFn.tabIndex = 0;
}
// 去考试
async function toMock(myExam: MyExam) {
  uni.navigateTo({
    url: `/pages/myMock/myMockPage?exerId=${myExam.id}`,
  });
  noticFn.tabIndex = 1;
}

function getDictName(dictIndex: string, dictKey: number) {
  return dictStore.getValue(dictIndex, dictKey);
}

const onClickItem = (e) => {
  if (current.value !== e.currentIndex) {
    current.value = e.currentIndex;
  }
  //根据选中的选项卡，刷新数据
  if (current.value === 0) {
    query(false); // 正式考试
  } else {
    query1(false); // 模拟考试
  }
};
const timeMove = ref(null);
//长按删除
const onTouchStart = (event, data) => {
  // event.preventDefault(); // 阻止默认事件
  clearTimeout(timeMove.value); // 清除之前的定时器
  delExamId.value = data.id;

  // 设置新的定时器
  timeMove.value = setTimeout(() => {
    // 长按打开弹窗
    alertDialog.value.open();
  }, 1000); // 设置长按时间为1000毫秒
};
const onTouchMove = () => {
  clearTimeout(timeMove.value); // 清除之前的定时器
};
const onTouchEnd = () => {
  clearTimeout(timeMove.value); // 清除之前的定时器
};
const dialogConfirm = async () => {
  //调用接口删除
  const { code, data } = await http.post("myExamMock/del", {
    id: delExamId.value,
  });

  if (code == 200) {
    query1(false); // 模拟考试
    uni.showToast({
      title: "删除成功",
      icon: "none",
    });
  }
};
const dialogCancel = () => {
  delExamId.value = "";
  alertDialog.value.close();
}

function calculateTimeDifference(dateStr, minutes) {
  var dateObj = new Date(dateStr);
  dateObj.setMinutes(dateObj.getMinutes() + minutes);

  // 将新的日期时间转换为 YYYY-MM-DD HH:MM:SS 格式返回
  var year = dateObj.getFullYear();
  var month = ("0" + (dateObj.getMonth() + 1)).slice(-2);
  var day = ("0" + dateObj.getDate()).slice(-2);
  var hours = ("0" + dateObj.getHours()).slice(-2);
  var min = ("0" + dateObj.getMinutes()).slice(-2);
  var sec = ("0" + dateObj.getSeconds()).slice(-2);

  return year + "-" + month + "-" + day + " " + hours + ":" + min;
}
</script>

<style lang="scss" scoped>
.my-exam {
  height: 100%;
}
.list_content {
}
/* 卡片圆角 阴影效果*/
.card {
  margin: 20rpx;
  background-color: #fff;
  border-radius: 20rpx;
  box-shadow: 0 0 20rpx 0 rgba(0, 0, 0, 0.1);
}
.test_time {
  height: 50rpx;
  margin: 6rpx;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  justify-content: flex-start;
  font-weight: 600;
}
.test_time_1 {
  height: 50rpx;
  margin: 6rpx;
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
  .timeInfo {
  }
}
.test_card_status {
  height: 50rpx;
  margin: 6rpx;
  display: flex;
  justify-content: center;
  align-items: flex-start;
  margin-left: 8rpx;
}

.mockB {
  text-align: center;
}
.tab {
  border-top: 1px solid #fff;
}
.tab ::v-deep .segmented-control__text {
  font-weight: bold;
}
.tab ::v-deep .segmented-control {
  height: 80rpx;
}
.test_status_info {
  display: flex;
  justify-content: space-around;
  width: 100%;
  align-content: center;
  .num {
    flex: 3;
    text-align: left;
  }
  .time {
    flex: 4;
    text-align: left;
  }
  .state {
    flex: 2;
    text-align: center;
    font-weight: bold;
  }
}
.stateImg {
  height: 100rpx;
  width: 100rpx;
}
.imgState {
  margin-top: -80rpx;
  margin-right: 20rpx;
}
.tab ::v-deep .segmented-control__item--button--first {
  border-radius: 0;
}
.tab ::v-deep .segmented-control__item--button--last {
  border-radius: 0;
}
.content ::v-deep .uni-load-more {
  height: 200rpx;
  align-items: flex-start;
  margin-top: 20rpx;
}
.tip{
  margin-left: 10rpx;
  margin-bottom: 20rpx;
  margin-top: 20rpx;
  font-size: 24rpx;
  color: #999;
}
</style>